package com.ybg.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;


/**
 * 加载数据源类，将${catalina.home}/ybg/conf下面的所有数据源文件加入到bean工厂中
 * 
 * @author zhouqixin
 */
public class DataSourceUtil {
	// Spring Bean 工厂
	public static DefaultListableBeanFactory beanFactory;

	/**
	 * 初始化
	 * 
	 * @param applicationContext
	 */
	public static void init(ApplicationContext applicationContext) {
		beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
		File dataDirectory = new File(System.getProperty("catalina.home") + File.separator + "ybg" + File.separator + "conf");
		
		// 数据源文件必定要是properties类型。ybg_cp.preperties 文件为奕报告数据源，由Spring自动加载
		File[] dataFiles = dataDirectory.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				String fileName = name.toLowerCase();
				
				if (fileName.endsWith(".properties")) {
					if(!fileName.startsWith("ybg_cp")) {
						return true;
					}
				}
				
				return false;
			}
		});
		
		for (int i = 0; i < dataFiles.length; i++) {
			String[] fileStrings = dataFiles[i].getName().split("\\.");
			String name = fileStrings[0];
			
			try (Reader reader = new InputStreamReader(new FileInputStream(dataFiles[i]), "UTF-8")) {
				Properties properties = new Properties();
				properties.load(reader);
				
				if (!properties.isEmpty()) {
					// 建立数据源的bean
					Map<String, Object> propertyMap = new HashMap<String, Object>();
					
					propertyMap.put("driverClassName", ConfigUtil.getString(properties, "sqlDriver"));
					propertyMap.put("url",             ConfigUtil.getString(properties, "sqlUrl"));
					propertyMap.put("username",        ConfigUtil.getString(properties, "sqlUsername"));
					propertyMap.put("password",        ConfigUtil.getString(properties, "sqlPassword"));
					propertyMap.put("initialSize",     ConfigUtil.getString(properties, "sqlInitialSize"));
					propertyMap.put("maxTotal",        ConfigUtil.getString(properties, "sqlMaxTotal"));
					propertyMap.put("maxIdle",         ConfigUtil.getString(properties, "sqlMaxIdle"));
					propertyMap.put("maxWaitMillis",   ConfigUtil.getString(properties, "sqlMaxWaitMillis"));
					
					BeanUtil.addBean(beanFactory, "org.apache.commons.dbcp2.BasicDataSource", name + "_dataSource", propertyMap, null, null, null, "close");

					// 建立jdbcTemplate的bean
					List<String> referenceConstrList = new ArrayList<String>();
					referenceConstrList.add(name + "_dataSource");
					BeanUtil.addBean(beanFactory, "org.springframework.jdbc.core.JdbcTemplate", name + "_jdbcTemplate", null, null, null, referenceConstrList, null);
					LogUtil.info("load datasource file {} success!", dataFiles[i].getAbsolutePath());
				}
			} catch (Exception e) {
				LogUtil.error("load datasource file {} fail!", dataFiles[i].getAbsolutePath());
			}
		}
	}
	
	/**
	 * 获取除开奕报告默认数据源的其它数据源
	 * 
	 * @param datasourceFileName 数据源配置文件名
	 * @return
	 */
	public static JdbcTemplate getJdbcTemplate(String datasourceFileName) {
		String id = datasourceFileName + "_jdbcTemplate";
		return beanFactory.getBean(id, JdbcTemplate.class);
	}
}